package com.heima.dfs.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.heima.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/dfs")
public class DfsController {

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {

        /**
         * p1 文件输入流
         * p2 文件大小
         * p3 文件后缀名
         * p4 元数据（可不加）
         */
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                StringUtils.getFilenameExtension(file.getOriginalFilename()),
                null);
        String fullPath = storePath.getFullPath();
        String webServerUrl = fdfsWebServer.getWebServerUrl();
        String realPath = webServerUrl + fullPath;
        Map<String , Object> dataMap = new HashMap<>();
        dataMap.put("url" , realPath);
        return ResponseResult.okResult(dataMap);
    }

    /**
     * 基于文件字符串形式完成文件上传
     * @param content         文件字符串
     * @param fileExtension   文件后缀名
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResponseResult<Map<String , Object>> uploadHtml(String content , String fileExtension) throws IOException {

        byte[] dataBytes = content.getBytes();
        ByteArrayInputStream is = new ByteArrayInputStream(dataBytes);
        /**
         * p1 文件输入流
         * p2 文件大小
         * p3 文件后缀名
         * p4 元数据（可不加）
         */
        StorePath storePath = fastFileStorageClient.uploadFile(is,
                dataBytes.length,
                fileExtension,
                null);
        String fullPath = storePath.getFullPath();
        String webServerUrl = fdfsWebServer.getWebServerUrl();
        String realPath = webServerUrl + fullPath;
        Map<String , Object> dataMap = new HashMap<>();
        dataMap.put("url" , realPath);
        return ResponseResult.okResult(dataMap);
    }

    /**
     * 根据文件地址删除文件
     * @param param
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseResult deleteHtml(@RequestBody Map<String , String> param){
        String url = param.get("url");
        fastFileStorageClient.deleteFile(url);
        return ResponseResult.okResult(null);
    }

}
